import loading from "components/loading";
import { Toast } from "vant";
import yz_pay from "components/ui_components/yz_pay";
import { yzPay } from "../../../utils/yz_pay"; //引入支付方法

var clicktag = 0;

export default {
  mixins: [yzPay],
  data() {
    return {
      isPayClick: false,
      isClick: 0,
      showPage: false,
      qrcode: "",
      showQR: false,
      show1: false,
      goodsInfo: {},
      order: {},
      dispatch: {},
      price: 0.0,
      // 订单数据
      datas: {},

      //支付
      order_ids: "",
      balance: 0,
      order_sn: "",
      money: "",
      buttons: [],
      pay_sn: "订单编号",
      order_pay_id: "",
      uid: "",
      payType: [],
      typename: "",

      payMuch: "0",
      showPacket: false,
      title_text:"支付",

      goodsDeductions:[],
      query:{
        orders: [],
        member_coupon_ids:[],
        address:'',
        store_profit_price:'',
        store_profit_uid:'',
        store_profit_image:''
      },
    };
  },

  activated() {
    this.isPayClick = false;
    this.isClick = 0;
    this.showQR = false;
    let profits = JSON.parse(localStorage.getItem("profits"));
    if(Object.keys(profits).length !==0 ) {
      this.query.store_profit_price = profits.price;
      this.query.store_profit_uid = Number(profits.uid);
      this.query.store_profit_image = profits.image;
    }
    this.goodsBuy();
  },
  mounted() {
    this.isClick = 0;
    this.popupSpecs = false;
  },
  computed: {},
  methods: {
    closePop() {
      this.show1 = false;
      this.isPayClick = false;
    },
    goodsBuy() {
      this.isClick = 1;
      this.query.orders = JSON.stringify(this._assembleDeduction());
      $http.get("plugin.store-profit.frontend.goods-buy.index", this.query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.setViewData(res);
            this.btnListIndex(parseFloat(res.total_price));
          } else {
            this.$dialog.alert({ message: response.msg }).then(() => {
              if (window.history.length <= 1) {
                this.$router.push(this.fun.getUrl("home"));
                return false
              } else {
                this.$router.go(-1)
              }
            });
          }
        },
        function(response) {
          console.log(response);
          // error callback
        }
      ).catch(err => {
        console.log(err);
      });
    },
    btnListIndex(price) {
      let btnQuery = {
        store_profit_price:price
      }
      $http.post("plugin.store-profit.frontend.payment-list.index", btnQuery, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.payType = res;
            this.buttons = res;
            let typeArr = [];
            for (let i = 0; i < this.payType.length; i++) {
              typeArr.push(this.payType[i]);
            }
            this.payType = typeArr;
            this.show1 = true;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
          // error callback
        }
      ).catch(err => {
        console.log(err);
      });
    },
    closePacket() {
      this.showPacket = false;
      // this.toRedirect(true);
    },
    //设置界面
    setViewData(data) {
      this.show1 = true;
      this.showPage = true;
      this.isClick = 0;
      this.datas = data;
      this.order_data = data.orders;
      let goodsDeductions = data.orders[0]?.order_deductions;
      if (Object.prototype.toString.call(goodsDeductions) === "[object Object]") {
        //判断是对象转化数组格式
        goodsDeductions = Object.values(res.orders[0]?.order_deductions);
      }
      this.goodsDeductions = goodsDeductions;
      this.payMuch = data.orders[0]?.order_goods_price;
      let orders = [];
      orders.push({
        pre_id: data.orders[0].pre_id
      });
      this.query.orders = orders;
      this.price = data.total_price; //设置总价格（合计）
    },

    //提交订单
    submit(val) {
      let url = "plugin.store-profit.frontend.create.index";
      this.query.orders = JSON.stringify(this._assembleDeduction());
      if (clicktag == 0) {
        clicktag = 1;
        if(this.isPayClick) {
          // 控制支付请求多次
          Toast("还在请求支付，请等待~");
          return;
        }
        this.isPayClick = true;
        $http.get(url, this.query, "提交中").then(
          (response)=> {
            this.isPayClick = false;
            if (response.result === 1) {
              this.order_ids = response.data.order_ids;
              this.getMultipleOrderInfo(val);
              setTimeout(function() {
                clicktag = 0;
              }, 1000);
            } else {
              this.isPayClick = false;
              this.$toast(response.msg);
            }
          });
      }
    },
    //抵扣选择响应
    discountHandle() {
      if (this.isClick === 0) {
        this.goodsBuy();
      }
    },
    _assembleDeduction() { //组合折扣的数据
      //修改提交的orders数据
      let deductions = [];
      let DeductionsData = [];
      let DeductionsId = [];
      let goodsDeductions = this.goodsDeductions;
      let newObj = {};
      DeductionsData = goodsDeductions.filter(item => {
        //筛选选中的爱心值，积分等等
        return item.checked === true;
      });
      DeductionsData.forEach(item => {
        //获取code值
        DeductionsId.push(item.code);
      });
      if(Array.isArray(this.query.orders)) {
        this.query.orders.push({
          deduction_ids: DeductionsId,
        });
        this.query.orders.forEach(item => {//如果有多个折扣遍历添加
          if (item) {
            newObj = { ...newObj, ...item };
          }
        });
      }
      if (Array.prototype.isPrototypeOf(this.query.orders) && this.query.orders.length !== 0) {
        //不是空数组的时候才添加对象
        deductions.push(newObj);
      }
      return deductions;
    },
    //多订单合并支付获取信息接口方法
    getMultipleOrderInfo(val) {
      //order.pay.wechatPay
      $http
        .get(
          "order.merge-pay",
          {
            order_ids: this.order_ids,
            pid: this.uid
          },
          "loading"
        )
        .then(
          (response)=> {
            if (response.result == 1) {
              this.order_sn = response.data.order_pay.pay_sn;
              this.balance = response.data.member.credit2;
              this.money = response.data.order_pay.amount;
              this.uid = response.data.order_pay.uid;
              this.order_pay_id = response.data.order_pay.id; //支付id
              this.confirm(val);
              localStorage.setItem('profits', JSON.stringify({}));
            } else {
              this.$dialog
                .confirm({ message: response.msg })
                .then(() => {
                  this.$router.push(this.fun.getUrl("home"));
                })
                .catch(() => {});
            }
          });
    }
  },
  components: { yz_pay, loading }
};
